package cn.com.czpb.client.module.news.view;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Picture;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import cn.com.czpb.client.R;
import cn.com.czpb.client.app.App;
import cn.com.czpb.client.config.CODE;
import cn.com.czpb.client.model.base.BaseEntity;
import cn.com.czpb.client.model.news.NewsDetailBean;
import cn.com.czpb.client.module.news.activity.ImgActivity;
import cn.com.czpb.client.module.news.activity.NewsDetailActivity;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.NetWorkHelper;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.SPUtil;

import java.util.HashMap;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/8/14.
 */

public class MyWebView implements View.OnClickListener {
    private Activity mActivity;
    private WebView webview;
    private int  textSize;
    private View root;

    private LinearLayout ll_root_id;
    private TextView tv_writertitle_id;
    private TextView tv_date_id;
    private ImageView img_subscribe_id;
    private ImageView img_remove_subscribe_id;
    private ImageView img_icon_id;
    private hidewhile404 myhide;
    private boolean isPraise=false;
    private boolean isDownPraise=false;
    private final SPUtil spu;
    private LinearLayout ll_404_id;
    private ImageView loading_img_id;
    private TextView refresh_id;
    private TextView error_id;
    private PlayListener listener;
    //    private NewsDetailBean mbean;
//    private String tid;
    private Handler handler;
    public static MyWebView instance(NewsDetailActivity activity, NewsDetailBean bean, String tid, hidewhile404 myhide, Handler handler){
        return new MyWebView(activity,bean,tid,myhide,handler);
    }
    public String getWebviewUrl(){
        return webview.getUrl();
    }
    public boolean canGoBack(){
        return webview.canGoBack();
    }
    public void goback(){
        if(webview.canGoBack()) {
            webview.goBack();
        }
    }
    public MyWebView(Activity mActivity,NewsDetailBean bean,String tid,hidewhile404 myhide,Handler handler) {
        this.myhide = myhide;
        this.mActivity = mActivity;
        this.handler=handler;
        spu = SPUtil.getInstance();
        initView(bean,tid);
    }
    public View getView(String url){
        Glide.with(mActivity).load(R.drawable.news_loading).asGif().into(loading_img_id);
        LogUtils.i("url5-->"+url);
        webview.loadUrl(url);
        return root;
    }
    public WebView getWebview(){
        return webview;
    }

    private void initView(NewsDetailBean bean, final String tid) {
//        this.mbean =bean;
//        this.tid = tid;
        SPUtil spu= SPUtil.getInstance();
        textSize = spu.getTextSize();
        LayoutInflater inflater = mActivity.getLayoutInflater();
        root =  inflater.inflate(R.layout.view_my_webview,null);
        webview = root.findViewById(R.id.webview_id);

        //-------------------------------------------------

        ll_root_id = root.findViewById(R.id.ll_root_id);//达人号跟布局
        //达人号头像
        img_icon_id = root.findViewById(R.id.img_icon_id);
        //达人号作者
        tv_writertitle_id = root.findViewById(R.id.tv_writertitle_id);
        //time
        tv_date_id = root.findViewById(R.id.tv_date_id);
        img_subscribe_id = root.findViewById(R.id.img_subscribe_id);
        img_remove_subscribe_id = root.findViewById(R.id.img_remove_subscribe_id);
        //---------------------------------------------------------------------
        ll_404_id = root.findViewById(R.id.ll_404_id);
        loading_img_id = root.findViewById(R.id.loading_img_id);
        refresh_id = root.findViewById(R.id.refresh_id);
        error_id = root.findViewById(R.id.error_id);
        refresh_id.setOnClickListener(this);
        error_id.setOnClickListener(this);
        //--------------------------------
        //-------------------------------------------------------
        webview.setPictureListener(new WebView.PictureListener() {
            int previousHeight;
            @Override
            public void onNewPicture(WebView w, Picture p) {
                int height = w.getContentHeight();
                if (previousHeight == height) return;
                previousHeight = height;
                LogUtils.e("WebView height" + height);
            }
        });
        WebSettings webSettings = webview.getSettings();
        webSettings.setSavePassword(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAppCachePath(App.getInstance().getAllDiskCacheDir());

//        webview.addJavascriptInterface(this, "imagelistner");
        webview.loadUrl("javascript:playNews()");
        webview.loadUrl("javascript:checkLogin()");
        webview.loadUrl("javascript:goMediaList()");
        webview.setHorizontalScrollBarEnabled(false);//水平不显示
        webview.setVerticalScrollBarEnabled(false); //垂直不显示
        if (NetWorkHelper.isNetConnected(mActivity)) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        webSettings.setAllowFileAccess(true);
        setWebViewTextSize(textSize);
        webview.setWebViewClient(new MyWebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                view.loadUrl("javascript:playNews()");
                view.loadUrl("javascript:checkLogin()");
                view.loadUrl("javascript:goMediaList()");
            }
        });
        webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {

                super.onReceivedTitle(view, title);
                // android 6.0 以下通过title获取
//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                    LogUtils.i("webview-->finish5");
//                    if (title.contains("404") || title.contains("500") || title.contains("Error")) {
//                        view.loadUrl("about:blank");// 避免出现默认的错误界面
//                        ll_404_id.setVisibility(View.VISIBLE);
//                        webview.setVisibility(View.GONE);
//                        myhide.hide();
//                    }
//                }
            }
        });
//        if ("0".equals(bean.getWemedia())){
//            ll_root_id.setVisibility(View.GONE);
//        }else{
//            ll_root_id.setVisibility(View.VISIBLE);
//            if (bean.getWriterinfo()!=null){
//                WriterInfoBean infoBean = bean.getWriterinfo();
//                Glide.with(mActivity).load(infoBean.getHeadimg()).crossFade().placeholder(R.drawable.default_bg).into(img_icon_id);
//                tv_writertitle_id.setText(infoBean.getNickname());
//                tv_date_id.setText(infoBean.getPublishTime());
//                if ("0".equals(infoBean.getIsfocus())){
//                    img_subscribe_id.setVisibility(View.VISIBLE);
//                    img_remove_subscribe_id.setVisibility(View.GONE);
//                }else{
//                    img_subscribe_id.setVisibility(View.GONE);
//                    img_remove_subscribe_id.setVisibility(View.VISIBLE);
//                }
//
//
//            }
//        }
    }

    private void setWebViewTextSize(int textSize) {
        LogUtils.e("setWebViewTextSize 字体-->2" + textSize);
        WebSettings settings = webview.getSettings();
        WebSettings.TextSize t = null;
        switch (textSize) {
            case CODE.textSize_big:
                settings.setTextZoom(115);
                break;
            case CODE.textSize_normal:
                settings.setTextZoom(100);
                break;
            case CODE.textSize_small:
                settings.setTextZoom(80);
                break;
            default:
                settings.setTextZoom(100);
                break;
        }
        webview.loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
    }


        //取消订阅
    private void removeFocusUser(String uid){
        Map<String ,String> map = new HashMap<>();
        if (spu.getUser()!=null){
            map.put("uid",spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(mActivity));
        map.put("focusid",uid);
        Factory.provideHttpService().removeFocusUser(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseEntity>() {
                    @Override
                    public void call(BaseEntity baseEntity) {
                        if ("200".equals(baseEntity.code)){
                            img_subscribe_id.setVisibility(View.VISIBLE);
                            img_remove_subscribe_id.setVisibility(View.GONE);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });

    }
    //订阅达人号
    private void focusUser(String uid){
        Map<String ,String> map = new HashMap<>();
        if (spu.getUser()!=null){
            map.put("uid",spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(mActivity));
        map.put("focusid",uid);
        Factory.provideHttpService().focusUser(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseEntity>() {
                    @Override
                    public void call(BaseEntity baseEntity) {
                        if ("200".equals(baseEntity.code)){
                            img_subscribe_id.setVisibility(View.GONE);
                            img_remove_subscribe_id.setVisibility(View.VISIBLE);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });

    }

    @android.webkit.JavascriptInterface
    public void openImage(String img) {
        Intent intent = new Intent();
        intent.putExtra("imgurl",img);
        intent.setClass(mActivity,ImgActivity.class);
        mActivity.startActivity(intent);
        mActivity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.refresh_id:
                webview.reload();
                break;
            case R.id.error_id:

                break;
        }

    }
    public interface hidewhile404{
        public abstract void hide();
    }
    // 监听
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            loading_img_id.setVisibility(View.GONE);
            LogUtils.i("webview-->finish");
            LogUtils.e(url);
            view.getSettings().setJavaScriptEnabled(true);

            super.onPageFinished(view, url);
            // html加载完成之后，添加监听图片的点击js函数
            webview.measure(0, 0);
            int measuredHeight = webview.getMeasuredHeight();
            LogUtils.e("webview height:"+measuredHeight);
            addImageClickListner();
//            ll_404_id.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);

            super.onPageStarted(view, url, favicon);
        }
//        @RequiresApi(android.os.Build.VERSION_CODES.M)
//        @Override
//        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
//            LogUtils.i("webview-->finish2");
//            super.onReceivedHttpError(view, request, errorResponse);
//            // 这个方法在6.0才出现
//
//            int statusCode = errorResponse.getStatusCode();
//            LogUtils.i("code-->"+statusCode);
//            System.out.println("onReceivedHttpError code = " + statusCode);
//            if (404 == statusCode || 500 == statusCode) {
//                view.loadUrl("about:blank");// 避免出现默认的错误界面
//                ll_404_id.setVisibility(View.VISIBLE);
//            }
//        }
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            LogUtils.i("webview-->finish3");
            super.onReceivedError(view, errorCode, description, failingUrl);
            LogUtils.i("webview-->error");
                ll_404_id.setVisibility(View.VISIBLE);
            webview.setVisibility(View.GONE);
            myhide.hide();
        }
    }
    // 注入js函数监听
    private void addImageClickListner() {
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，
        //函数的功能是在图片点击的时候调用本地java接口并传递url过去
        webview.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imagelistner.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()");
    }
    public void setOnPlayClickListener(PlayListener listener) {
        this.listener = listener;
    }
    public interface PlayListener{
        void playMM();
    }
    @JavascriptInterface
    public void playContent(){
        LogUtils.i("JavascriptInterface-->"+666);
        handler.sendEmptyMessage(666);
    }

    @JavascriptInterface
    public void checkUserLogin(){
        LogUtils.i("JavascriptInterface-->"+777);
        handler.sendEmptyMessage(777);
    }

    @JavascriptInterface
    public void goForMediaList(String uid,String tid){
        LogUtils.i("JavascriptInterface-->"+uid+"-->"+tid);
        PageCtrl.start2SubscribeDetailActivity(mActivity,uid,tid);
//        Message message=Message.obtain();
//        Bundle bundle=new Bundle();
//        bundle.putString("uid", uid);
//        bundle.putString("tid", tid);
//        message.setData(bundle);//bundle传值，耗时，效率低
//        handler.sendMessage(message);//发送message信息
//        handler.sendEmptyMessage(888);
    }
}
